import { observable, action } from 'mobx';
import * as API from '../apis/news';
import * as Util from '../util/index';
import { isFunction, isEmpty } from 'lodash';

const catchApiError = Util.catchApiError;
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

export class NewsStore {
  @observable publishType = '0';// 0 为外部
  @observable outerDatas = {
    companyName: '',
    newsList: [],
  };
  @observable selectedKeys = [];
  @observable listDatas = {
    list: [],
    pageNum: 0,
    publishType: '0',
    title: '',
    titleNews: [],
  };
  @observable loadingList = false;
  @observable isFirstLoad = true;
  @observable isDetail = false;
  @observable contentDatas = {
    attachList: [],
    content: {
      doccontent: '',
      doccreatedate: '',
      doclastmoddate: '',
      docsubject: '',
    },
  };

  @action
  setState = (params = {}) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
    return this;
  }

  setPublishTypeAndId = (publishType = '0', id = '', cb) => {
    this.publishType = publishType;
    this.selectedKeys = [id];
    isFunction(cb) && cb();
  }

  init = (params = {}) => {
    const publishType = this.publishType;
    publishType == '0' ? this.getOuter() : this.getList({ id: this.selectedKeys[0] });
  }

  getList = (params = {}) => {
    this.loadingList = true;
    API.getList(params).then(catchApiError).then((result) => {
      this.listDatas = { ...result, pageNum: result.pageNum && result.pageNum > 0 ? result.pageNum : 10 };
      this.loadingList = false;
      this.isFirstLoad = false;
    });
  }

  getOuter = (params = {}) => {
    API.getOuter(params).then(catchApiError).then((result) => {
      this.outerDatas = result;
      const id = !isEmpty(this.selectedKeys) ? this.selectedKeys[0] : result.newsList[0] && result.newsList[0].id;
      this.selectedKeys = [id];
      this.getList({ id });
    });
  }

  getContent = (params = {}) => {
    API.getContent(params).then(catchApiError).then((result) => {
      this.contentDatas = result;
    });
  }
}
